/**
 * 输入n位数字的组件，默认控制为4位
 * @author: minzhang
 * @update: 2016-11-24
 */

import React, { PropTypes } from 'react';
import { Input } from 'antd';

const CommonCodeInput = React.createClass({
  getInitialState() {
    return {
      value: this.props.value || '',
    };
  },
	componentWillReceiveProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      const value = nextProps.value;
      this.setState({value});
    }
  },
  handleChange(e) {
		const len = this.props.len || 4;
		const number = e.target.value.replace(/[^\d]/g, '').slice(0, len);
		
		this.setState({ value: number });
		
    const onChange = this.props.onChange;
    onChange && onChange(number);
  },
  render() {
    return (
      <Input
        type="text"
				size={this.props.size}
        disabled={this.props.disabled}
        placeholder={this.props.placeholder}
        value={this.state.value}
        onChange={this.handleChange}
      />
    );
  },
});

CommonCodeInput.propTypes = {
  value: PropTypes.any,
  onChange: PropTypes.func,
};

export default CommonCodeInput;